package com.giveu.signature.common.util;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.commons.io.FileUtils;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
//import org.apache.poi.xwpf.converter.core.BasicURIResolver;
//import org.apache.poi.xwpf.converter.core.FileImageExtractor;
//import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
//import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;

import com.giveu.common.utils.security.Base64;

import fr.opensagres.poi.xwpf.converter.core.BasicURIResolver;
import fr.opensagres.poi.xwpf.converter.core.FileImageExtractor;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLConverter;
import fr.opensagres.poi.xwpf.converter.xhtml.XHTMLOptions;

public class DocToHtmlUtil {
	/**
	 * doc转换为html
	 *
	 * @param fileName
	 * @param outPutFile
	 * @throws TransformerException
	 * @throws IOException
	 * @throws ParserConfigurationException
	 */
	public static void doc2Html(String fileName, String outPutFile) throws TransformerException, IOException, ParserConfigurationException {
		long startTime = System.currentTimeMillis();
		HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(fileName));
		WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
		wordToHtmlConverter.setPicturesManager(new PicturesManager() {
			public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
				return suggestedName;
			}
		});
		wordToHtmlConverter.processDocument(wordDocument);
		// 保存图片
		List<Picture> pics = wordDocument.getPicturesTable().getAllPictures();
		if (pics != null) {
			for (int i = 0; i < pics.size(); i++) {
				Picture pic = (Picture) pics.get(i);
				try {
					pic.writeImageContent(new FileOutputStream("E://temp//" + pic.suggestFullFileName()));
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}
		}
		Document htmlDocument = wordToHtmlConverter.getDocument();
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		DOMSource domSource = new DOMSource(htmlDocument);
		StreamResult streamResult = new StreamResult(out);

		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer serializer = tf.newTransformer();
		serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		serializer.setOutputProperty(OutputKeys.METHOD, "html");
		serializer.transform(domSource, streamResult);
		out.close();
		writeFile(new String(out.toByteArray()), outPutFile);
		System.out.println("Generate " + outPutFile + " with " + (System.currentTimeMillis() - startTime) + " ms.");
	}
	/**
	 * 写文件
	 *
	 * @param content
	 * @param path
	 */
	public static void writeFile(String content, String path) {
		FileOutputStream fos = null;
		BufferedWriter bw = null;
		try {
			File file = new File(path);
			fos = new FileOutputStream(file);
			bw = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"));
			bw.write(content);
		} catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			try {
				if (bw != null)
					bw.close();
				if (fos != null)
					fos.close();
			} catch (IOException ie) {
			}
		}
	}
	

	public static void main(String[] args) throws Exception {
//		docx2Html("D:\\test.docx", "D:\\test3.html");
		System.out.println(wordToHtml("D:\\20190513.docx"));
//		String str="总会在某一个回眸的时刻醉了流年，濡湿了柔软的心.总会有某一个回眸的时刻醉了流年，濡湿了柔软的心";
//		str=str.replaceAll("总会在.+?流年", "总会有某一个回眸的时刻醉了22222222222222222222222222222流年");
//		System.out.println(str);
		
//		System.out.println(stringToUnicode("本"));
	}
	/**
	 * 字符串转unicode
	 * 
	 * @param str
	 * @return
	 */
	public static String stringToUnicode(String str) {
		StringBuffer sb = new StringBuffer();
		char[] c = str.toCharArray();
		for (int i = 0; i < c.length; i++) {
			sb.append("\\u" + Integer.toHexString(c[i]));
		}
		return sb.toString();
	}

	/**
	 * unicode转字符串
	 * 
	 * @param unicode
	 * @return
	 */
	public static String unicodeToString(String unicode) {
		StringBuffer sb = new StringBuffer();
		String[] hex = unicode.split("\\\\u");
		for (int i = 1; i < hex.length; i++) {
			int index = Integer.parseInt(hex[i], 16);
			sb.append((char) index);
		}
		return sb.toString();
	}

	public static String wordToHtml(String filePath) throws Exception{
		if(filePath.endsWith(".doc")){
			String content=convert2Html(filePath);
			return content;
		}
		if(filePath.endsWith(".docx")){
			String content=docxToHtml(filePath);
//			String.fromCharCode("".replace("/[&#;]/g", ""));
			return content;
		}
		return null;
	}
	
	/**
	 * docx格式word转换为html
	 *
	 * @param fileName   docx文件路径
	 * @param outPutFile html输出文件路径
	 * @throws TransformerException
	 * @throws IOException
	 * @throws ParserConfigurationException
	 */
	public static void docx2Html(String fileName, String outPutFile) throws IOException {
		String fileOutName = outPutFile;
		long startTime = System.currentTimeMillis();
		XWPFDocument document = new XWPFDocument(new FileInputStream(fileName));
		XHTMLOptions options = XHTMLOptions.create().indent(4);
		// 导出图片
		File imageFolder = new File("E:/temp/images");
		options.setExtractor(new FileImageExtractor(imageFolder));
		// URI resolver  word的html中图片的目录路径
		options.URIResolver(new BasicURIResolver("images"));
		File outFile = new File(fileOutName);
		outFile.getParentFile().mkdirs();
		OutputStream out = new FileOutputStream(outFile);
		XHTMLConverter.getInstance().convert(document, out, options);
		System.out.println("Generate " + fileOutName + " with " + (System.currentTimeMillis() - startTime) + " ms.");

	}
	//docx转换html
    public static String docxToHtml4(String fileName) throws Exception {
        XWPFDocument docxDocument = new XWPFDocument(new FileInputStream(fileName));
        XHTMLOptions options = XHTMLOptions.create();
        // 转换htm11
        ByteArrayOutputStream htmlStream = new ByteArrayOutputStream();
        XHTMLConverter.getInstance().convert(docxDocument, htmlStream, options);
        String htmlStr = htmlStream.toString();
        return htmlStr;
    }
    
    
	public static String docxToHtml(String sourceFileName){
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		XWPFDocument document = null;
		XHTMLOptions options = XHTMLOptions.create().indent(0);
		try {
			document = new XWPFDocument(new FileInputStream(sourceFileName));
			XHTMLConverter.getInstance().convert(document, baos, options); 		
		} catch (Exception e) {
			throw new RuntimeException(e);
		}finally {
			try {
				baos.close();
			} catch (IOException e) {
			}
			try {
				document.close();
			} catch (IOException e) {
			}
		}
		String content =new String(baos.toByteArray());
		content=content.replaceAll("<span.+>","");
		content=content.replaceAll("</span>","");
		content=content.replaceAll("white-space:pre-wrap;","");
		content=content.replaceAll("text-align:center;","text-align:center;font-size:16.0pt;font-weight:bold;");
		content=content.replaceAll("<div style=\"width:595.3pt;.+\">","<div style=\"width:500pt;margin:20pt;\">");
		content=content.replaceAll("\\R+","");
		content=content.replaceAll("<style>.+</style>","<style>div { width: 680px; line-height:25px; letter-spacing:0.6px; font-family: 华文楷体; } p { text-indent:35.0px; }</style>");
//		content=getStringNoBlank(content);
//		content=content.replaceAll("style="," style=");
		return content;    	
	}
	
	public static String getStringNoBlank(String str) {   
        if(str!=null && !"".equals(str)) {   
            Pattern p = Pattern.compile("\\R+");   //\\s*|\t|
            Matcher m = p.matcher(str);   
            String strNoBlank = m.replaceAll("");   
            return strNoBlank;   
        }else {   
            return str;   
        }        
	}

	//docx转换html
	public static String docxToHtml2(String fileName) throws IOException {
		XWPFDocument docxDocument = new XWPFDocument(new FileInputStream(fileName));
		// 配置
		XHTMLOptions options = XHTMLOptions.create();
		// 设置图片存储路径
		String path = System.getProperty("java.io.tmpdir");
		String firstImagePathStr = path + "/" + String.valueOf(System.currentTimeMillis());
		options.setExtractor(new FileImageExtractor(new File(firstImagePathStr)));
		options.URIResolver(new BasicURIResolver(firstImagePathStr));
		// 转换html
		ByteArrayOutputStream htmlStream = new ByteArrayOutputStream();
		XHTMLConverter.getInstance().convert(docxDocument, htmlStream, options);
		String htmlStr = htmlStream.toString();
		// 将image文件转换为base64并替换到html字符串里 
		String middleImageDirStr = "/word/media";
		String imageDirStr = firstImagePathStr + middleImageDirStr;
		File imageDir = new File(imageDirStr);
		String[] imageList = imageDir.list();
		if (imageList != null) {
			for (int i = 0; i < imageList.length; i++) {
				String oneImagePathStr = imageDirStr + "/" + imageList[i];
				File oneImageFile = new File(oneImagePathStr);
				String imageBase64Str = new String(Base64.decode(FileUtils.readFileToByteArray(oneImageFile)), "UTF-8");
				htmlStr = htmlStr.replace(oneImagePathStr, "data:image/png;base64," + imageBase64Str);
			}
		}
		//删除图片路径
		File firstImagePath = new File(firstImagePathStr);
		FileUtils.deleteDirectory(firstImagePath);
		System.out.println(htmlStr);
		return htmlStr;

	}
	//doc 转 html 
	public static String convert2Html(String fileName)
			throws TransformerException, IOException,
			ParserConfigurationException {

		HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(fileName));//WordToHtmlUtils.loadDoc(new FileInputStream(inputFile));
		//兼容2007 以上版本
		WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
				DocumentBuilderFactory.newInstance().newDocumentBuilder()
				.newDocument());
		wordToHtmlConverter.processDocument(wordDocument);
		//解析html
		Document htmlDocument = wordToHtmlConverter.getDocument();      
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		DOMSource domSource = new DOMSource(htmlDocument);      
		StreamResult streamResult = new StreamResult(out);
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer serializer = tf.newTransformer();    
		serializer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		serializer.setOutputProperty(OutputKeys.METHOD, "HTML");
		serializer.transform(domSource, streamResult);
		out.close();
		String htmlContent=new String(out.toByteArray());
		//替换UEditor无法识别的转义字符
		String htmlContent1=htmlContent.replaceAll("&ldquo;","\"").replaceAll("&rdquo;","\"").replaceAll("&mdash;","-");       
		return htmlContent1;
	}

	public static void convert2Html(String fileName, String outPutFile)
			throws TransformerException, IOException,
			ParserConfigurationException {
		HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(fileName));//WordToHtmlUtils.loadDoc(new FileInputStream(inputFile));
		WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
				DocumentBuilderFactory.newInstance().newDocumentBuilder()
				.newDocument());
		wordToHtmlConverter.setPicturesManager( new PicturesManager() {
			public String savePicture(byte[] content,
					PictureType pictureType, String suggestedName,
					float widthInches, float heightInches )
			{
				return "test/"+suggestedName;
			}
		} );
		wordToHtmlConverter.processDocument(wordDocument);
		//save pictures
		List pics=wordDocument.getPicturesTable().getAllPictures();
		if(pics!=null){
			for(int i=0;i<pics.size();i++){
				Picture pic = (Picture)pics.get(i);
				System.out.println();
				try {
					pic.writeImageContent(new FileOutputStream("D:/test/"
							+ pic.suggestFullFileName()));
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}  
			}
		}
		Document htmlDocument = wordToHtmlConverter.getDocument();
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		DOMSource domSource = new DOMSource(htmlDocument);
		StreamResult streamResult = new StreamResult(out);

		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer serializer = tf.newTransformer();
		serializer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		serializer.setOutputProperty(OutputKeys.METHOD, "html");
		serializer.transform(domSource, streamResult);
		out.close();
		writeFile(new String(out.toByteArray()), outPutFile);
	}


}
